<script setup lang="ts">
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Search, Minus, Plus } from "@element-plus/icons-vue";
import { storeToRefs } from "pinia";
import { ElMessage } from "element-plus";
import {
  saveOrUpdateApiPost,
  channelDetailApiGet,
  channelAllocateProductApiPost,
} from "@/api/userMangement";
import { productLinkConfigListPost } from "@/api/allProduct";

import useInstance from "@/hooks/useInstance";
import { useComListData } from "@/store/list";

const { listCollect } = storeToRefs(useComListData());
const active = ref(0);
defineOptions({
  name: "addListAd",
});
const props = defineProps({
  channelList: {
    type: Array as any,
    default: () => [],
  },
});
const emit = defineEmits(["refresh", "searchEdit"]);
const { global } = useInstance();
const dialogBasic = ref({
  title: "新建渠道商",
  visible: false,
  width: 600,
  height: 550,
  showFooter: true,
  marginTop: "10vh",
});
const editAndAddType = ref();
const ruleFormRef = ref<FormInstance>();
const productFormRef = ref<FormInstance>();
const showEnvAndScene = ref(false)

const options = [
  {
    label: "初始化",
    value: 1,
  },
  {
    label: "审核通过",
    value: 2,
  },
  {
    label: "审核拒绝",
    value: 3,
  },
];
const productOption = [
  {
    label: "是",
    value: 1,
  },
  {
    label: "否",
    value: 2,
  },
];
const channelForm = reactive<any>({
  channelKey: null, //  渠道Key 商务洽谈时使用 四个字符（数字加字符）
  // channelCode: "", // 渠道编码 后端生成
  channelName: null, // 渠道名称
  channelMerchantCode: null,
  mobile: null, // 手机号
  auditStatus: null, //  审核状态
  auditTime: null, // 审核时间
  extInfo: [
    {
      key: null,
      value: null,
    },
  ],
  remarks: null, // 备注
});
const productForm = reactive<any>({
  channelCode: null, //  渠道编码
  channelProductName: null, //  渠道产品名称
  productCode: null, //  产品编码
  schemeCode: null, //  方案编码
  environmentCode: null, //   环境
  scenarioCode: null, //  场景
  enableReporting: null, //  是否开启上报
  reportingPlatformCode: null, //  上报平台
  enableGrantEquity: null, //  是否开启发放权益
});
const rules = reactive<FormRules>({
  channelKey: [
    {
      required: true,
      trigger: "blur",
      message: "请输入渠道Key",
    },
    {
      pattern: /^[0-9a-zA-Z]{4,5}$/,
      trigger: "blur",
      message: "请输入四或五位数字或则英文字符",
    },
  ],
  channelCode: [
    {
      required: true,
      trigger: "blur",
      message: "请输入渠道编码",
    },
  ],
  channelName: [
    {
      required: true,
      trigger: "blur",
      message: "请输入渠道名称",
    },
  ],
  mobile: [
    {
      required: true,
      trigger: "blur",
      message: "请输入手机号",
    },
    {
      trigger: "blur",
      message: "请输入正确的手机号",
      pattern: /^1[3-9]\d{9}$/,
    },
  ],
  auditStatus: [
    {
      required: true,
      trigger: "blur",
      message: "请选择审核状态",
    },
  ],
  channelMerchantCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择渠道商",
    },
  ],
  auditTime: [
    {
      required: true,
      trigger: "blur",
      message: "请选择审核时间",
    },
  ],
});
const productFormRules = reactive<FormRules>({
  enableGrantEquity: [
    {
      required: true,
      trigger: "blur",
      message: "请选择是否开启发放权益",
    },
  ],
  reportingPlatformCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择上报平台",
    },
  ],
  enableReporting: [
    {
      required: true,
      trigger: "blur",
      message: "请选择是否开启上报",
    },
  ],
  productCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择渠道编码",
    },
  ],
  schemeCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择方案",
    },
  ],
  environmentCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择环境",
    },
  ],
  scenarioCode: [
    {
      required: true,
      trigger: "blur",
      message: "请选择场景",
    },
  ],
});
const addOrEdit = ref();
//显示弹框
const show = (type: string, row?: any) => {
  editAndAddType.value = type;
  dialogBasic.value.visible = true;
  if (type === "add") {
    addOrEdit.value = "add";
    dialogBasic.value.title = "渠道新增";
    dialogBasic.value.height = 500;
    global.$resetForm(ruleFormRef.value, channelForm);
    channelForm.auditTime = null;
    channelForm.extInfo = [
      {
        key: null,
        value: null,
      },
    ];
    resetForm();
  } else {
    addOrEdit.value = "edit";
    dialogBasic.value.height = 550;

    global.$resetForm(ruleFormRef.value, channelForm);
    dialogBasic.value.title = "渠道编辑";
    global.$objCopy(channelForm, row);

    const arr = JSON.parse(row.extInfo);
    if (arr && Object.keys(arr).length > 0) {
      channelForm.extInfo = [];
      Object.keys(arr).forEach((item) => {
        channelForm.extInfo.push({
          key: item,
          value: arr[item],
        });
      });
    } else {
      channelForm.extInfo = [
        {
          key: null,
          value: null,
        },
      ];
    }
  }
};
const onClose = () => {
  dialogBasic.value.visible = false;
  showEnvAndScene.value = false
  channelForm.extInfo = [
    {
      key: null,
      value: null,
    },
  ];
  envAndSceneList.value = [];
  newSceneCodeList.value = [];
  active.value = 0;
  resetForm();
};
const onConfirmAndClose = async () => {
  await ruleFormRef.value?.validate(async (isOk) => {
    if (isOk) {
      const arr: any = {};
      channelForm.extInfo &&
        channelForm.extInfo.forEach((item: any) => {
          // 数据判断
          if (item.key) {
            arr[item.key] = item.value;
          }
        });

      const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr);
      const res = await saveOrUpdateApiPost({
        ...channelForm,
        extInfo: newArr,
      });
      if (res.code == 20000) {
        ElMessage({
          type: "success",
          message: channelForm.id ? "渠道编辑成功" : "渠道新增成功",
        });
        emit("searchEdit");
        onClose();
      }
    } else {
      ElMessage({
        type: "error",
        message: channelForm.id
          ? "渠道编辑失败 请重试！"
          : "编辑新增失败 请重试！",
      });
    }
  });
};
const onConfirm = async () => {
  console.log(channelForm.extInfo);

  await ruleFormRef.value?.validate(async (isOk) => {
    if (isOk) {
      const arr: any = {};
      channelForm.extInfo &&
        channelForm.extInfo.forEach((item: any) => {
          // 数据判断
          if (item.key) {
            arr[item.key] = item.value;
          }
        });

      const newArr = Object.keys(arr).length == 0 ? "{}" : JSON.stringify(arr);
      const res = await saveOrUpdateApiPost({
        ...channelForm,
        extInfo: newArr,
      });
      if (res.code == 20000) {
        ElMessage({
          type: "success",
          message: channelForm.id ? "渠道编辑成功" : "渠道新增成功",
        });
        // onClose();
        active.value++;
        setTimeout(async () => {
          const nowRes = await channelDetailApiGet({ id: res.data });
          //     // 最新的数据 直接给第一个表单
          global.$objCopy(channelForm, nowRes.data);

          productForm.channelCode = nowRes.data.channelCode;
          productForm.channelProductName = nowRes.data.channelName;
        }, 300);
      }
    } else {
      ElMessage({
        type: "error",
        message: channelForm.id
          ? "渠道编辑失败 请重试！"
          : "编辑新增失败 请重试！",
      });
    }
  });
};
const btnAdd = () => {
  channelForm.extInfo.push({
    key: null,
    value: null,
  });
};
const removeDomain = (item: any) => {
  const index = channelForm.extInfo.indexOf(item);
  if (index !== -1) {
    channelForm.extInfo.splice(index, 1);
  }
};
const resetForm = () => {
  ruleFormRef.value?.resetFields();
  productFormRef.value?.resetFields();
};
const nextStep = () => {
  active.value--;
  // 判断数据
  const arr = JSON.parse(channelForm.extInfo);
  if (arr && Object.keys(arr).length > 0) {
    channelForm.extInfo = [];
    Object.keys(arr).forEach((item) => {
      channelForm.extInfo.push({
        key: item,
        value: arr[item],
      });
    });
  } else {
    channelForm.extInfo = [
      {
        key: null,
        value: null,
      },
    ];
  }
};
const onConfirmImg = async () => {
  await productFormRef.value?.validate(async (isOk) => {
    if (isOk) {
      const res = await channelAllocateProductApiPost(productForm);
      if (res.code == 20000) {
        ElMessage({
          type: "success",
          message: "渠道关联产品成功",
        });
        onClose();
        emit("refresh");
      }
    } else {
      ElMessage({
        type: "error",
        message: "渠道关联产品失败 请重试！",
      });
    }
  });
};
defineExpose({
  show,
});
/* 筛选产品基础链接的环境和场景 */
const productChange = (item: any) => {
  let arr = []
  if (!item) {
    showEnvAndScene.value = false
    productForm.schemeCode = null
    productForm.scenarioCode = null;
    productForm.environmentCode = null;
  } else {
    searchProductLinkList(item);
    productForm.scenarioCode = null;
    productForm.environmentCode = null;
    arr = listCollect.value.productList.filter(it => it.productCode == item)
    productForm.schemeCode = arr[0].schemeCode

    if (arr[0].productType == 2) {
      // 要
      showEnvAndScene.value = true

    } else {
      // 不要
      showEnvAndScene.value = false
      productForm.scenarioCode = null;
      productForm.environmentCode = null;
    }
  }
};
const envAndSceneList = ref<any>([]);
const newSceneCodeList = ref<any>([]);
let result = {};
const transFormArr = (data: any) => {
  result = {};
  // 遍历数据并填充映射
  data.forEach((item: any) => {
    const envKey = item.environment;
    const envName = item.environmentName;

    if (!result[envKey]) {
      result[envKey] = {
        key: envKey,
        name: envName,
        value: [],
      };
    }

    const scenarioKey = item.scenario;
    const scenarioName = item.scenarioName;

    // 检查是否已经存在相同的 scenario
    const existingScenario = result[envKey].value.find(
      (scenario) => scenario.key === scenarioKey
    );
    if (!existingScenario) {
      result[envKey].value.push({
        key: scenarioKey,
        name: scenarioName,
      });
    }
  });

  // 将映射转换为数组
  const finalResult = Object.values(result);
  console.log(finalResult);
  envAndSceneList.value = finalResult;
};
const searchProductLinkList = async (item: string) => {
  envAndSceneList.value = [];
  newSceneCodeList.value = [];
  const res = await productLinkConfigListPost({
    productCode: item,
  });
  // 如果只有一条数据 如果多条数据 如果 没有查询到 联合会员需要提示
  if (res.code == 20000 && !res.data) {
    productForm.scenarioCode = null;
    productForm.environmentCode = null;
    if (showEnvAndScene.value) {
      return ElMessage({
        type: "warning",
        message: "该产品无基础链接 请添加",
      });
    } else {
      return
    }

  }
  if (res.code == 20000 && res.data && res.data.length == 1) {
    transFormArr(res.data);
    productForm.scenarioCode = res.data[0]?.scenario;
    productForm.environmentCode = res.data[0]?.environment;
  } else {
    transFormArr(res.data);
  }
};
const environmentCodeChange = (item: any) => {
  productForm.scenarioCode = null;
  newSceneCodeList.value = [];
  const arr = envAndSceneList.value.filter((it: any) => it.key == item);
  newSceneCodeList.value = arr[0]?.value;
};
</script>

<template>
  <SysDialogSlot :title="dialogBasic.title" :width="dialogBasic.width" :height="dialogBasic.height"
    :show-footer="dialogBasic.showFooter" :visible="dialogBasic.visible" :draggable="true"
    :margin-top="dialogBasic.marginTop" @on-close="onClose" destroy-on-close @on-confirm="onConfirm">
    <template v-slot:content>
      <div class="channel-form">
        <div style="margin: 10px 0px" v-if="editAndAddType == 'add'">
          <el-steps :active="active" finish-status="success" align-center>
            <el-step title="渠道基础信息" />
            <el-step title="渠道产品关联" />
          </el-steps>
        </div>
        <el-form v-show="active === 0" ref="ruleFormRef" :model="channelForm" :rules="rules" label-width="120px"
          class="demo-ruleForm" status-icon>
          <el-form-item label="渠道商" prop="channelMerchantCode">
            <el-select v-model="channelForm.channelMerchantCode" placeholder="请选择渠道商" filterable>
              <el-option v-for="item in channelList" :key="item.channelMerchantCode" :label="item.channelMerchantName"
                :value="item.channelMerchantCode" />
            </el-select>
          </el-form-item>
          <el-form-item label="渠道Key" prop="channelKey">
            <AddInput v-model:model-value="channelForm.channelKey" maxlength="5" clearable></AddInput>
          </el-form-item>

          <el-form-item label="渠道名称" prop="channelName">
            <AddInput v-model:model-value="channelForm.channelName" clearable></AddInput>
          </el-form-item>
          <el-form-item label="手机号码">
            <AddInput v-model:model-value="channelForm.mobile" clearable></AddInput>
          </el-form-item>
          <el-form-item label="审核状态" prop="auditStatus" v-if="channelForm.id">
            <el-select v-model="channelForm.auditStatus" placeholder="请选择审核状态">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="备注" prop="remarks">
            <!-- <el-input v-model="channelForm.remarks" /> -->
            <AddInput v-model:model-value="channelForm.remarks" clearable></AddInput>
          </el-form-item>
          <el-form-item v-for="(domain, index) in channelForm.extInfo" :key="index" :label="'信息扩展' + (index + 1)">
            <el-row style="width: 100%" justify="space-around">
              <el-col :span="6">
                <el-input v-model="domain.key" placeholder="请输入value" :autosize="{ minRows: 2, maxRows: 4 }"
                  type="textarea"></el-input>
              </el-col>
              <el-col :span="15">
                <el-input v-model="domain.value" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                  placeholder="请输入value" clearable></el-input>
              </el-col>
              <el-col :span="2">
                <el-button type="danger" style="margin-top: 12px" size="small" @click="removeDomain(domain)"
                  :icon="Minus" />
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="添加信息扩展">
            <el-button type="primary" @click="btnAdd" :icon="Plus" style="width: 100%" />
          </el-form-item>
        </el-form>
        <el-form v-show="active === 1" ref="productFormRef" :model="productForm" :rules="productFormRules"
          label-width="120px" class="demo-ruleForm" status-icon>
          <el-form-item label="产品编码" prop="productCode">
            <el-select v-model="productForm.productCode" @change="productChange" placeholder="请选择产品编码" filterable
              clearable>
              <el-option v-for="item in listCollect.productList" :key="item.key" :label="item.value"
                :value="item.key" />
            </el-select>
          </el-form-item>

          <el-form-item label="方案编码" prop="schemeCode">
            <el-select v-model="productForm.schemeCode" placeholder="请选择方案编码" filterable>
              <el-option v-for="item in listCollect.equitySchemeList" :key="item.key" :label="item.value"
                :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="环境" prop="environmentCode" v-if="showEnvAndScene">
            <el-select v-model="productForm.environmentCode" placeholder="请选择环境" clearable
              @change="environmentCodeChange" filterable>
              <el-option v-for="item in envAndSceneList" :key="item.key" :label="`${item.key} - ${item.name}`"
                :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="场景" prop="scenarioCode" v-if="showEnvAndScene">
            <el-select v-model="productForm.scenarioCode" placeholder="请选择场景" filterable>
              <el-option v-for="item in newSceneCodeList" :key="item.key" :label="`${item.key} - ${item.name}`"
                :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否开启上报" prop="enableReporting">
            <el-select v-model="productForm.enableReporting" placeholder="请选择是否开启上报" filterable>
              <el-option v-for="item in productOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <template v-if="productForm.enableReporting == 1">
            <el-form-item label="上报平台" prop="reportingPlatformCode">
              <el-select v-model="productForm.reportingPlatformCode" placeholder="请选择上报平台" filterable>
                <el-option v-for="item in listCollect.reportingPlatformCodeList" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="上报平台">
              <el-select v-model="productForm.reportingPlatformCode" placeholder="请选择上报平台" filterable>
                <el-option v-for="item in listCollect.reportingPlatformCodeList" :key="item.value" :label="item.label"
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </template>

          <el-form-item label="是否开启发放权益" prop="enableGrantEquity">
            <el-select v-model="productForm.enableGrantEquity" placeholder="请选择是否开启发放权益" filterable>
              <el-option v-for="item in productOption" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <template v-slot:myFooter>
      <div class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="success" @click="onConfirmAndClose"
          v-if="active === 0 && editAndAddType == 'edit'">确定</el-button>

        <el-button @click="nextStep" v-if="active !== 0 && editAndAddType == 'add'">上一步</el-button>
        <el-button type="success" @click="onConfirm" v-if="active === 0 && editAndAddType == 'add'">下一步</el-button>
        <el-button type="success" @click="onConfirmImg" v-if="active === 1 && editAndAddType == 'add'">确定</el-button>
      </div>
    </template>
  </SysDialogSlot>
</template>

<style lang="scss" scoped>
.channel-form {
  // height: 500px;
  // overflow: auto;
}
</style>
